package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
//    新增菜品
    public R<String> insert(@RequestBody Category category) {
        log.info("前端响应数据：{}", category);
        categoryService.save(category);
        return R.success("新增菜品成功");

    }

    //    分页查询
    @GetMapping("/page")
    public R<IPage<Category>> iPageR(Integer page, Integer pageSize) {
        log.info("当前页码：{}，每页查询条数：{}", page, pageSize);
//        分页构造器
        Page<Category> page1 = new Page<>(page, pageSize);
//        降序排列
//        条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);

        categoryService.page(page1, lqw);
        return R.success(page1);
    }

    //    修改
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("修改数据：{}", category);
        categoryService.updateById(category);
        return R.success("修改成功");

    }

    //    删除
    @DeleteMapping
    public R<String> delete(Long id) {
        log.info("删除id：{}", id);
        categoryService.delete(id);
        return R.success("删除成功");
    }

    //    菜品管理中增加请求响应
    @GetMapping("/list")
    public R<List<Category>> creatList(Category category) {
//        条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType() != null, Category::getType, category.getType());
//        添加排序条件
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);

        return R.success(list);

    }

}
